# @Author : DGGem
# @Email : 1254656865@qq.com
# @Project : hids
import time
import xml.etree.ElementTree as ET  # xml

from app.tools.regular_matching_rule import LogInfoFetch
from app.tools.monitor import Monitor
from app.config import *
from app.threat_rules.custom import get_user_defined

m = Monitor()  # 实例化
lgf = LogInfoFetch()


# nginx日志分析
def nginx_log(path):
    file = open(path)  # 打开文件
    file.seek(0, 2)  # 光标移向最后
    while True:
        try:
            lists = file.readlines()  # 一次性读取整个文件内容，并按行返回到list
            if len(lists) == 0:
                time.sleep(5)
                continue
            for aline in lists:
                data = lgf.get_info(aline)  # 正则提取url信息
                m.get_ip_ua_to_redis(data['ip'], data['user_agent'])  # 检测是否频繁访问
                m.get_ip_path(data['ip'], data['user_agent'], data['path'])  # 检测是否存在sql注入或xss攻击
        except:
            file.close()


# 输入一行日志进行分析
def line():
    log_line = input("请输入一条nginx日志：")
    data = lgf.get_info(log_line)
    print(data)
    m.get_ip_path(data['ip'], data['user_agent'], data['path'])  # 检测是否存在sql注入或xss攻击


# php.ini配置项
def php_safe():
    m.get_php_ini(php_safe_ini['path'], php_safe_ini['funcs'])


# 用户自定义web检查规则
def user_defined_rule():
    details = input("请输入自定义的规则标题（sql注入、xss攻击）：")
    level = input("请输入触发该规则的严重程度（信息、低危、中危、高危、严重）：")
    words = input("请输入触发该规则的语法（支持多个，以','分割）：")
    get_user_defined(details, level, words)


# 系统配置项检查（sshd）
def sshd_safe():
    m.get_sshd_conf(sshd_config['path'], sshd_config['para'])


# 检查目录下的文件是否是木马文件
def check_file_trojan(path):
    m.check_trojan(path)


# 检测系统执行计划指令
def crontab(path):
    m.check_crontab(path)


# 获取cpu的消耗
def check_cpu():
    m.cpu_data()


# 检测CronJob防止提权
def check_cron_jobs(path):
    m.check_cron_jobs_defaule(path)


# 根据CVE扫描当前系统漏洞
def scan_vulnerable():
    tree = ET.parse('/opt/CVE/allitems.xml')  # ET去打开xml文件
    # root = tree.getroot()  # 获取根标签
    root = ET.fromstring('cve')
    print(root)


if __name__ == '__main__':
    # nginx_log(nginx_access_log)  # nginx日志
    # line()
    # php_safe()
    # user_defined_rule()
    # sshd_safe()
    # check_file_trojan(in_a_word)
    # crontab(crontab_rule)
    # check_cpu()
    # check_cron_jobs(cron_jobs)
    scan_vulnerable()
# 118.116.107.72 - - [23/Jul/2022:12:34:40 +0000] "GET /index.php?floor HTTP/1.1" 200 69003 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 Edg/103.0.1264.62" "-"
